package com.trsvax.tapestry.instrumentation.components;

import java.util.Collections;
import java.util.List;

import org.apache.log4j.spi.LoggingEvent;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

import com.trsvax.tapestry.instrumentation.ThreadDetail;
import com.trsvax.tapestry.instrumentation.services.TapestryAppender;

public class ThreadDetailView {
	@Inject
	private TapestryAppender tapestryAppender;

	@Inject
	private ComponentResources componentResources;

	@Inject
	private BeanModelSource beanModelSource;

	@Inject
	private Messages messages;

	@Parameter(required = true)
	@Property
	private ThreadDetail detail;

	@Property
	private LoggingEvent event;

	@Property
	@Parameter
	private List<String> loggerNames;
	@Property
	private String loggerName;

	@BeginRender
	void init() {
	}

	private long lastTime;
	private long totalTime;

	public Long getTotalTime() {
		return detail.getEndTime() - detail.getStartTime();
	}

	public Long getDuration() {
		Long duration = 0L;
		if (lastTime == 0) {
			lastTime = event.timeStamp;
		}
		duration = event.timeStamp - lastTime;

		totalTime += duration;
		lastTime = event.timeStamp;
		return duration;
	}

	public Long getTime() {
		return totalTime;
	}

	public List<LoggingEvent> getLogger() {
		lastTime = detail.getStartTime();

		List<LoggingEvent> logs = null;
		if (loggerName.equals("All")) {
			logs = detail.getLogs();
		} else if (loggerName.equals("Page")) {
			logs = detail.getList(detail.getPageClass());
		} else
			logs = detail.getList(loggerName);

		if (logs == null || logs.size() == 0) {
			return Collections.EMPTY_LIST;
		}

		lastTime = 0;
		totalTime = logs.get(0).timeStamp - detail.getStartTime();

		return logs;
	}

	public String getPrettyLoggerName() {
		return messages.format(loggerName);
	}

}
